<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import LTable from "@/components/layout/LTable.vue";
import EditForm from "./components/EditForm.vue";
import { TableImport, TableExport, TableSetting, TableFilter } from "@/components/sofastui/table";
import { getPage, deleteObj } from "@/services/api/demo";
import { usePagination } from "vue-request";
import { useOptions } from "@/hooks/useOptions/useOptions";
import { _dataFormatter } from "@/utils/formatter";
import { FullScreenTwo } from "@icon-park/vue-next";
import { fields } from "./constant";

const { options } = useOptions({
    names: ["projectDemandType", "projectDemandStatus"],
});

const editFormRef = ref();

const searchFields = computed(() => {
    return fields.filter(item => item.search !== false).map(item => ({ ...item }));
});

const importFields = computed(() => {
    return fields.filter(item => item.search !== false).map(item => ({ ...item }));
});

const exportFields = computed(() => {
    return fields.filter(item => item.search !== false).map(item => ({ ...item }));
});

const radio = ref("-1");
const radioOptions = ref([{
    label: '全部',
    value: '-1',
}, {
    label: '部门',
    value: '1',
}, {
    label: '个人',
    value: '2',
}]);

const searchFormData = reactive<{
    searchKey: string;
    filter: {
        relation: "or" | "and";
        fields: { field: string; oper: string; value?: any }[];
    };
    order: [string, "descending" | "ascending"][];
}>({
    searchKey: "",
    filter: { relation: "and", fields: [] },
    order: [],
});
const pageSizes = [10, 20, 50, 100, 200];

const multipleSelection = ref<any[]>([]);

const { run, refresh, data, current, loading, pageSize, total } = usePagination(
    getPage,
    {
        defaultParams: [
            {
                ...searchFormData,
            },
        ],
        pagination: {
            currentKey: "currentPage",
            pageSizeKey: "pageSize",
            totalKey: "data.count",
        },
    },
);

// 创建
const handelAdd = () => {
    editFormRef.value?.show("add", {});
};

// 更新
// const handelUpdate = (data: any) => {
//   editFormRef.value?.show("update", data);
// };

// 查看
const handelView = (data: any) => {
    editFormRef.value?.show("view", data);
};

// 删除
const del = (data: any) => {
    ElMessageBox.confirm("删除当前数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            deleteObj(data.id).then(() => {
                ElMessage({
                    type: "success",
                    message: "删除成功",
                });
                refresh();
            });
        })
        .catch(() => {
            ElMessage("已取消删除");
        });
};

// 批量操
const handleBatch = (type: string) => {
    switch (type) {
        case "dels":
            ElMessageBox.confirm(
                `批量删除当前选中${multipleSelection.value.length}条数据, 是否继续?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                },
            )
                .then(() => {
                    console.log(multipleSelection);
                })
                .catch(() => {
                    ElMessage("已取消删除");
                });
            break;

        default:
            break;
    }
};

// 表格多选
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
};

const handleSortChange = (val: {
    column: any;
    prop: string;
    order: "descending" | "ascending" | null;
}) => {
    const { column, prop, order } = val;
    if (order !== null) {
        searchFormData.order = [[prop, order]];
    } else {
        searchFormData.order = [];
    }
    run({
        ...searchFormData,
        currentPage: 1,
        pageSize: pageSize,
    });
    console.log(column, prop, order);
};
</script>

<template>
    <div class="h-full px-3 pt-3">
        <LTable>
            <template #top-left>
                <el-segmented v-model="radio" :options="radioOptions" />
            </template>
            <template #table-bar-left>
                <el-space>
                    <!-- 新增 -->
                    <el-button type="primary" icon="Notification" @click="handelAdd">新增</el-button>
                    <!-- 数据导入弹窗 -->
                    <TableImport :fields="importFields" :downTmp="'/download/userImportTmp.xlsx'"
                        @refreshDataList="refresh()" />
                </el-space>
            </template>
            <template #table-bar-right>
                <el-space>
                    <el-input v-model="searchFormData.searchKey" class="w-50 m-2" placeholder="请输入关键词搜索"
                        suffix-icon="Search" clearable @change="
                            run({
                                ...searchFormData,
                                currentPage: 1,
                                pageSize: pageSize,
                            })
                            " />
                    <el-button-group class="ml-4">
                        <!-- 表格高级搜素 -->
                        <TableFilter v-model="searchFormData.filter" :fields="searchFields" @change="
                            run({
                                ...searchFormData,
                                currentPage: 1,
                                pageSize: pageSize,
                            })
                            " />
                        <el-tooltip effect="dark" content="刷新" placement="top">
                            <el-button type="primary" icon="Refresh" plain @click="refresh()"
                                :loading="loading"></el-button>
                        </el-tooltip>
                        <!-- 表格设置 -->
                        <TableSetting :fields="exportFields" />
                        <!-- 数据导出弹窗 -->
                        <TableExport :fields="exportFields" :downTmp="'/download/userImportTmp.xlsx'"
                            @refreshDataList="refresh()" />
                    </el-button-group>
                </el-space>
            </template>

            <template #body>
                <el-table :data="data?.data?.rows || []" style="width: 100%; height: 100%" height="100%"
                    max-height="100%" v-loading="loading" table-layout="auto" scrollbar-always-on border
                    row-class-name="s-table-row" row-key="id" @selection-change="handleSelectionChange"
                    @sort-change="handleSortChange">
                    <template #empty>
                        <el-empty>
                            <template #description>
                                <span class="mr-1">暂无内容，点击</span>
                                <el-button type="primary" link @click="refresh()" :loading="loading">刷新</el-button>
                            </template>
                        </el-empty>
                    </template>
                    <el-table-column type="selection" width="44" align="center" />
                    <el-table-column type="index" fixed label="序号" width="60" align="center">
                        <template #default="scope">
                            <div class="row-index">{{ scope.$index + 1 }}</div>
                            <div class="row-expand-btn">
                                <el-tooltip class="box-item" effect="dark" content="展开记录" placement="top">
                                    <full-screen-two class="cursor-pointer" theme="outline" size="18" fill="#999"
                                        @click="handelView(scope.row)" />
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="no" label="日志编号" width="220" />
                    <el-table-column prop="content" label="工作内容" width="220" />
                    <el-table-column prop="other" label="需要的支持、风险、问题" width="220" />
                    <el-table-column prop="desc" label="备注" width="220" />
                    <el-table-column prop="plannedStartTime" label="计划开始时间" width="140" align="center" sortable="custom"
                        :formatter="(_row: any, _column: any, cellValue: string, _index: number) =>
                            _dataFormatter(cellValue)
                            " />
                    <el-table-column prop="plannedEndTime" label="计划结束时间" width="140" align="center" sortable="custom"
                        :formatter="(_row: any, _column: any, cellValue: string, _index: number) =>
                            _dataFormatter(cellValue)
                            " />
                    <el-table-column prop="completionDegree" label="完成进度" width="140" align="center"
                        sortable="custom" />
                    <el-table-column prop="plannedTime" label="预计工时(h)" width="140" align="center" sortable="custom" />
                    <el-table-column prop="actualTime" label="实际工时(h)" width="140" align="center" sortable="custom" />
                    <el-table-column prop="project" label="关联项目" width="220">
                        <template #default="scope">{{ scope.row.project.name }}</template>
                    </el-table-column>
                    <el-table-column prop="demand" label="关联需求" width="220">
                        <template #default="scope">{{ scope.row.demand.title }}</template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="创建时间" width="140" align="center" sortable="custom"
                        :formatter="(_row: any, _column: any, cellValue: string) =>
                            _dataFormatter(cellValue)
                            " />
                    <el-table-column label="操作" width="80" align="center">
                        <template #default="scope">
                            <el-button size="small" icon="Delete" type="danger" title="删除" @click="del(scope.row)" />
                        </template>
                    </el-table-column>
                </el-table>
            </template>
            <template #bottom-left>
                <div class="demonstration">
                    <el-button text bg size="small" type="danger" :disabled="!multipleSelection.length"
                        @click="handleBatch('dels')">删除</el-button>
                </div>
            </template>
            <template #bottom-right>
                <el-pagination size="small" background v-model:current-page="current" v-model:page-size="pageSize"
                    :total="total" :page-sizes="pageSizes" :default-page-size="20"
                    layout="total, sizes, prev, pager, next, jumper"></el-pagination>

            </template>
        </LTable>
    </div>
    <!-- 修改表单 -->
    <EditForm ref="editFormRef" :options="options" @refreshDataList="refresh()" />

</template>

<style lang="less" scoped>
.height-50 {
    height: calc(100vh - 60px - 1.5rem - 50px);
}

.height-150 {
    height: calc(100vh - 60px - 1.5rem - 129px);
}
</style>